﻿using System;
using biz.ritter.javapi.lang;
using Nofs.Net.Common.Interfaces.Library;
using Nofs.Net.Common.Interfaces.Cache;
using Nofs.Net.Common.Interfaces.Factories;
using Nofs.Net.Common.Interfaces;
using Nofs.Net.nofs.metadata.interfaces;
using Nofs.Net.Common.Interfaces.Domain;
using Db4objects.Db4o;


namespace Nofs.Net.nofs.Db4o
{
    public class Db4oPersistenceFactory : IPersistenceFactory
    {
        private IObjectContainer _objDb;
        private IObjectContainer _metaDb;
        private IDomainObjectContainerManagerInternal _containerManager;
        private IKeyCache _keyCache;
        private IStatMapper _statMapper;

        private IObjectContainer GetObjDb(String objectStore)
        {
            if (_objDb == null)
            {
                _objDb = Db4oFactory.OpenFile(objectStore);
            }
            return _objDb;
        }

        private IObjectContainer GetMetaDb(String metaDb)
        {
            if (_metaDb == null)
            {
                _metaDb = Db4oFactory.OpenFile(metaDb);
            }
            return _metaDb;
        }

        //public IDomainObjectContainerManagerInternal<object> CreateContainerManager(
        //        String objectStore, String metdataStore, ILogManager logManager,
        //        IStatMapper statMapper, IKeyCache keyCache, IFileObjectFactory fileObjectFactory,
        //        IAttributeAccessor attributeAccessor)
        //{

        //}

        public IDomainObjectContainerManagerInternal<object> CreateContainerManager(
                String objectStore, String metdataStore, ILogManager logManager,
                IStatMapper statMapper, IKeyCache keyCache, IFileObjectFactory fileObjectFactory,
                IAttributeAccessor attributeAccessor) //throws Exception 
        {
            if (_containerManager == null)
            {
                _containerManager = new DomainObjectContainerManager(
                        GetObjDb(objectStore), statMapper, keyCache, fileObjectFactory, attributeAccessor);
            }
            return _containerManager;
        }

        public IKeyCache CreateKeyCache(String objectStore, String metdataStore, ILogManager logManager) //throws Exception 
        {
            if (_keyCache == null)
            {
                _keyCache = new KeyCache(GetObjDb(objectStore));
            }
            return _keyCache;
        }

        public IStatMapper CreateStatMapper(
                String objectStore, String metdataStore,
                Class fileObjectStatClass, ILogManager logManager) //throws Exception 
        {
            if (_statMapper == null)
            {
                _statMapper = new Db4oStatMapper(GetMetaDb(metdataStore), fileObjectStatClass);
            }
            return _statMapper;
        }

    }
}
